package com.foruo.learn.thread;

/**
 * 测试线程状态
 * java.lang.Thread.State
 *
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
 *
 * @author GaoYuan
 * @date 2018/6/22 上午8:42
 */
public class TestThread {

    public static void main(String[] args){
        // 启动一个线程占有 doThis 方法的锁
        Thread thread0 = new Thread(()->{
            doThis("thread0");
            System.out.println("thread0 执行完成\n");
        });
        thread0.start();

        Thread thread = new Thread(()->{
            doThis("thread");
            System.out.println("thread 执行完成");
        });
        // NEW  执行之前肯定是new
        System.out.println("1 >> "+thread.getState());
        thread.start();
        // RUNNABLE 可执行或运行中，jvm在处理
        System.out.println("2 >> "+thread.getState());

        // 只要有等待时间，则thread肯定走到了 doThis 方法，此时被别的线程独占
        try {
            Thread.sleep(500);
        }catch (Exception e){

        }
        // BLOCKED
        System.out.println("3 >> "+thread.getState());

        try {
            Thread.sleep(3400);
        }catch (Exception e){

        }
        // TIMED_WAITING
        System.out.println("4 >> "+thread.getState());

        try {
            Thread.sleep(2000);
        }catch (Exception e){

        }
        // TERMINATED
        System.out.println("5 >> "+thread.getState());


    }

    public synchronized static void doThis(String name){
        try {
            System.out.println(name + " 执行 doThis，等2s");
            Thread.sleep(2000);
        }catch (Exception e){

        }
    }

}
